package com.lagou.client;

import com.lagou.server.service.entity.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
//    private String para;

    private RpcRequest rpcRequest;

    private RpcClients.RpcServer rpcServer;


    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() {
        rpcServer.setLastProcTime(System.currentTimeMillis());
        long start = System.nanoTime();
        context.writeAndFlush(rpcRequest);
        // 10秒超时
        try {
            wait(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        long end = System.nanoTime();
        long duration = (end - start) / 1000000L;
        rpcServer.setLastProcDuration((int) duration);
        return result;
    }

    /*
     设置参数
     */
//    void setPara(String para) {
//        this.para = para;
//    }


    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public RpcClients.RpcServer getRpcServer() {
        return rpcServer;
    }

    public void setRpcServer(RpcClients.RpcServer rpcServer) {
        this.rpcServer = rpcServer;
    }
}
